﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using static System.Net.Mime.MediaTypeNames;

namespace FileOperation
{
    internal class Program
    {
        static string DeleteComments(string s)
        {
            string[] str = s.Split(new string[] {"//"}, StringSplitOptions.RemoveEmptyEntries);
            // Console.WriteLine(str[0]);
            return str[0];
        }
        static void HandleOriFile()
        {
            try
            {
                // 文件输入输出流
                FileStream fin = new FileStream("Test.cs", FileMode.Open, FileAccess.Read);
                FileStream fout = new FileStream("Test.txt", FileMode.Create, FileAccess.Write);
                int lineNum = 0, numOfWords_ori = 0;
                using (StreamReader reader = new StreamReader(fin, Encoding.UTF8))
                {
                    using (StreamWriter writer = new StreamWriter(fout, Encoding.UTF8))
                    {                        
                        string pattern = @"\b\w+\b";
                        string s = null;
                        while ((s = reader.ReadLine()) != null)
                        {
                            lineNum++; // 统计原始行数
                            MatchCollection matches = Regex.Matches(s, pattern);
                            numOfWords_ori += matches.Count; // 统计原始单词数目
                        }
                        Console.WriteLine($"原始文件共有{lineNum}行，{numOfWords_ori}个单词");

                        reader.BaseStream.Seek(0, SeekOrigin.Begin); // 从头读起
                        s = null;
                        while ((s = reader.ReadLine()) != null)
                        {
                            //.Trim()删除开头结尾无意义空格和制表符，以便判断空行
                            if (string.IsNullOrEmpty(s.Trim())) continue; // 删除空行
                            s = Program.DeleteComments(s); // 删除注释
                            if (string.IsNullOrEmpty(s.Trim())) continue;// 删除失去注释后的空行
                            writer.WriteLine(s);
                        }
                    }
                }
            }
            catch (FileNotFoundException e)
            {
                Console.WriteLine($"文件{e.FileName}没找到！");
            }
            catch (IOException e2)
            {
                Console.WriteLine(e2);
            }
        }
        static void HandleNewFile()
        {
            try
            {
                // 文件输入输出流
                FileStream fin = new FileStream("Test.txt", FileMode.Open, FileAccess.Read);
                int lineNum = 0, numOfWords_new = 0;
                using (StreamReader reader = new StreamReader(fin, Encoding.UTF8))
                {                    
                    string pattern = @"\b\w+\b";
                    string s = null;
                    while ((s = reader.ReadLine()) != null)
                    {
                        lineNum++; // 统计原始行数
                        MatchCollection matches = Regex.Matches(s, pattern);
                        numOfWords_new += matches.Count; // 统计原始单词数目
                    }
                    Console.WriteLine($"格式化文件共有{lineNum}行，{numOfWords_new}个单词");
                }
            }
            catch (FileNotFoundException e)
            {
                Console.WriteLine($"文件{e.FileName}没找到！");
            }
            catch (IOException e2)
            {
                Console.WriteLine(e2);
            }
        }
        static void CountWords()
        {
            try
            {
                FileStream fin = new FileStream("Test.txt", FileMode.Open, FileAccess.Read);
                using (StreamReader reader = new StreamReader(fin, Encoding.UTF8))
                {
                    string pattern = @"\b\w+\b";
                    string s = reader.ReadToEnd();
                    MatchCollection matches = Regex.Matches(s, pattern);
                    List<string> words = new List<string>(); // 存储所有单词
                    foreach (Match match in matches)
                    {
                        words.Add(match.Value);
                    }
                    // 用LINQ查询各个单词出现次数，并降序排列
                    var wordCounts = words
                                    .GroupBy(word => word)
                                    .Select(group => new { Word = group.Key, Count = group.Count() }) // 匿名方法，生成新类。
                                    .OrderByDescending(word => word.Count);
                    // 将LINQ查询结果存入Dictionary中
                    Dictionary<string, int> dic = wordCounts.ToDictionary(word => word.Word, word => word.Count);
                    foreach(var item in dic)
                    {
                        Console.WriteLine($"\"{item.Key}\":\t{item.Value}");
                    }
                }
            }
            catch (FileNotFoundException e)
            {
                Console.WriteLine($"文件{e.FileName}没找到！");
            }
            catch (IOException e2)
            {
                Console.WriteLine(e2);
            }
        }
        static void Main(string[] args)
        {
            // 统计原文件
            Program.HandleOriFile();
            // 统计格式化后的文件
            Program.HandleNewFile();
            // 统计各个单词出现次数
            Program.CountWords();
        }
    }
}
